package com.qf.listener;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class DelQueueListener {

    // 死信队列做记录可以
//    @RabbitListener(queues = "dle-queue")
    public void msg(String msg, Channel channel, Message message) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println(format + " --> 死信队列做记录，这些消息都是消费不了的:" + msg + ",deliveryTag:" + deliveryTag);
        channel.basicAck(deliveryTag, false);
    }

    // 消费者消息有误队列中的消息
    @RabbitListener(queues = "businessQueue")
    public void msg2(String msg, Channel channel, Message message) throws IOException {
        System.out.println("业务队列开始消息消费消息：" + msg);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        if ("error".equals(msg)) {
            System.out.println("【" + msg + "】这个消息消费者消费不了，应该给NACK");
            channel.basicNack(deliveryTag, false, false);
//            channel.basicReject(deliveryTag,false);/// nack
        } else {
            System.out.println("【" + msg + "】这个消息消费者可以消费，应该给ACK");
            // 必须要加入队列，因为业务队列已经配置了死信
            channel.basicAck(deliveryTag, false);
        }
    }

    @RabbitListener(queues = "maxlength-queue")
    public void msg3(String msg, Channel channel, Message message) {

        // 1.每获取一个消息都启动一个线程去消费
        new Thread(() -> {
            System.out.println("开始消费消息:" + msg);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            try {
                channel.basicAck(deliveryTag, false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

    }
}
